package com.blog.interceptor;

import com.blog.exception.ExceptionEnum;
import com.blog.exception.MyException;
import com.blog.utils.JwtUtils;
import com.blog.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Pattern;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    private static final Pattern EXCLUDE_PATH_PATTERN = Pattern.compile(
            "^(/articles(/\\d+|/byTag/\\d+|/byUserId/\\d+|/byCondition+|/sortBySupport)?" +
                    "|/articletags/\\d+" +
                    "|/comments/article/\\d+" +
                    "|/email" +
                    "|/hobbies/\\d+" +
                    "|/notices(/\\d+)?" +
                    "|/sendQuestion" +
                    "|/tags" +
                    "|/register" +
                    "|/login" +
                    "|/login/password" +
                    "|/users/\\d+)$"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果请求为 OPTIONS 请求，则返回 true,否则需要通过jwt验证
//        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
//            System.out.println("OPTIONS请求，放行");
//            return true;
//        }
        String uri = request.getRequestURI();
        System.out.println("请求路径: " + uri);

        // 如果路径匹配排除模式，则不进行拦截
        if (EXCLUDE_PATH_PATTERN.matcher(uri).matches()) {
            return true;
        }
        
        System.out.println(request.getServletPath());

        String authorizationHeader = request.getHeader("Authorization");
        String token = null;
        // 检查 Authorization 头部是否存在并且以 "Bearer " 开头
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            throw new MyException(ExceptionEnum.NOT_LOGIN);
            //return false;
        }
        // 提取 token
        token = authorizationHeader.substring(7);
        log.info("从请求头中获取的令牌：{}",token);

        //解析token，如果解析失败，返回错误结果
        try {
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            log.info("令牌解析失败!");
            throw new MyException(ExceptionEnum.INVALID_LOGIN);
            //return false;
        }

        Claims claims = JwtUtils.parseJWT(token);
        String id =claims.get("id").toString();
        UserContext.setUserId(id);

        //放行
        return true;


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear(); // 清除ThreadLocal中的用户ID
    }

}